package main

import (
	"encoding/hex"
	"fmt"
	"net"
	"time"
	// "github.com/axgle/mahonia"
)

type ST_Statistic struct {
	rx_count uint32
	tx_count uint32
}

var st_statistic ST_Statistic

func HandleConn(conn net.Conn) {
	defer conn.Close()
	buf := make([]byte, 1024)
	//initial send command to client
	strcmd := "010300000001840A"
	cmd_buf, _ := hex.DecodeString(strcmd)
	st_statistic.tx_count += 1
	conn.Write(cmd_buf)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("Read error: ", err)
			return
		}
		if n > 4 {
			st_statistic.rx_count += 1
			st_statistic.tx_count += 1
			// response client
			conn.Write(cmd_buf)
			time.Sleep(time.Second)
			fmt.Println("Display the count:", st_statistic)
		}
		// decoder := mahonia.NewDecoder("gbk")
		// _, cdata, _ := decoder.Translate(buf[:n], true)
		// fmt.Println(string(cdata))
		fmt.Println(string(buf[:n]))
	}
}

func main() {
	println("### TCP server startup! ###")
	listen, err := net.Listen("tcp", ":8888")
	if err != nil {
		fmt.Println("listen error: ", err)
		return
	}
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("listen error: ", err)
			break
		}
		go HandleConn(conn)
	}
}
